

import { AppDataSource } from '@/config/AppDataSource';
import { CreateIndexInfoDto, UpdateIndexInfoDto, QueryIndexInfoDto, DeleteIndexInfoDto } from '@/dto/indexInfo.dto';
import { IndexInfo } from '@/entities/indexInfo.entity';
import { In } from 'typeorm';
export class IndexInfoRepository {
    private repositor = AppDataSource.getRepository(IndexInfo);
    constructor() { }

    async findExcludeId(data: UpdateIndexInfoDto) {
        const conflictCategory = await this.repositor
            .createQueryBuilder('indexInfo')
            .where('indexInfo.id != :id', { id: data.id })
            .andWhere('(indexInfo.filedName = :filedName)', { filedName: data.filedName })
            .getOne();
        return conflictCategory
    }


    async indexInfoExists(filedName: string) {
        const c = await this.repositor.findOne({
            where: [
                { filedName },
            ],
        });
        return c;
    }

    async findById(id: number) {

        const item = await this.repositor.findOneBy({
            id
        })
        return item;
    }

    async create(data: CreateIndexInfoDto): Promise<IndexInfo> {
        const indexInfo = new IndexInfo();
        
            indexInfo.status = data.status;
            indexInfo.filedName = data.filedName;
            indexInfo.comment = data.comment;
            indexInfo.indexType = data.indexType;
        
        const result = await this.repositor.save(indexInfo)
        // console.log("result", result)
        return result;
    }
    async update(data: UpdateIndexInfoDto) {
        const indexInfo = new IndexInfo();
        indexInfo.id = data.id;
        
            indexInfo.status = data.status;
            indexInfo.filedName = data.filedName!;
            indexInfo.comment = data.comment;
            indexInfo.indexType = data.indexType;

        return this.repositor.save(indexInfo);

    }



    async selectList(reqData: QueryIndexInfoDto) {
        const { page, pageSize, filedName, orderBy,  comment,status,fromDate, toDate } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('indexInfo')
            .select([
                
            'indexInfo.id',
            'indexInfo.createdAt',
            'indexInfo.updatedAt',
            'indexInfo.status',
            'indexInfo.filedName',
            'indexInfo.comment',
            'indexInfo.indexType',
            ]);

        if (filedName) {
            queryBuilder.andWhere('indexInfo.filedName LIKE :filedName', { filedName: `%${filedName}%` });
        }
        if (comment) {
            queryBuilder.andWhere('indexInfo.comment LIKE :comment', { comment: `%${comment}%` });
        }
        if (status) {
            queryBuilder.andWhere('indexInfo.status = :status', { status });
        }
                // 添加创建日期范围查询
        if (fromDate && toDate) {
            queryBuilder.andWhere('indexInfo.createdAt BETWEEN :fromDate AND :toDate', {
                fromDate: new Date(fromDate),
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        } else if (fromDate) {
            queryBuilder.andWhere('indexInfo.createdAt >= :fromDate', {
                fromDate: new Date(fromDate)
            });
        } else if (toDate) {
            queryBuilder.andWhere('indexInfo.createdAt <= :toDate', {
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        }
        const [sortBy, sortOrder] = orderBy.split(" ")
        const [indexInfo, total] = await queryBuilder
            .orderBy(`indexInfo.${sortBy}`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
        return {
            list: indexInfo,
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: DeleteIndexInfoDto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }
}

export default new IndexInfoRepository();
    
    